package com.sitia.jd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sitia.common.CustomException;
import com.sitia.common.core.domain.entity.SysRole;
import com.sitia.common.core.domain.entity.SysUser;
import com.sitia.common.utils.DateUtils;
import com.sitia.common.utils.SecurityUtils;
import com.sitia.common.utils.StringUtils;
import com.sitia.common.utils.uuid.IdUtils;
import com.sitia.jd.domain.MxOrder;
import com.sitia.jd.domain.MxOrderDetail;
import com.sitia.jd.domain.dto.JdCouponDto;
import com.sitia.jd.domain.dto.jdUserInfoDto;
import com.sitia.jd.domain.vo.MxOrderVo;
import com.sitia.jd.enums.MxCouponType;
import com.sitia.jd.mapper.MxOrderMapper;
import com.sitia.jd.service.IMxOrderService;
import com.sitia.jd.util.JdUtils;
import com.sitia.jd.util.LoginUserUtil;
import com.sitia.system.domain.SysCustomer;
import com.sitia.system.mapper.SysCustomerMapper;
import com.sitia.system.mapper.SysUserMapper;
import com.sitia.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * mx订单Service业务层处理
 * 
 * @author sitia
 * @date 2023-05-22
 */
@Service
@Slf4j
public class MxOrderServiceImpl  extends ServiceImpl<MxOrderMapper, MxOrder>  implements IMxOrderService
{
    @Resource
    private MxOrderMapper mxOrderMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysCustomerMapper customerMapper;
    @Resource
    private ISysConfigService sysConfigService;

    /**
     * 查询mx订单
     * 
     * @param id mx订单主键
     * @return mx订单
     */
    @Override
    public MxOrder selectMxOrderById(String id)
    {
        return mxOrderMapper.selectMxOrderById(id);
    }

    /**
     * 查询mx订单列表
     * 
     * @param mxOrder mx订单
     * @return mx订单
     */
    @Override
    public List<MxOrder> selectMxOrderList(MxOrder mxOrder)
    {
        if (mxOrder.getPresetTimes() != null) {
            mxOrder.setPresetTimeStar(mxOrder.getPresetTimes()[0]);
            mxOrder.setPresetTimeEnd(mxOrder.getPresetTimes()[1]);
        }
        return mxOrderMapper.selectMxOrderList(mxOrder);
    }

    /**
     * 新增mx订单
     * 
     * @param mxOrder mx订单
     * @return 结果
     */
    @Override
    public int insertMxOrder(MxOrder mxOrder)
    {
        Date now = DateUtils.getNowDate();
        addCustomerInfo(mxOrder);
        mxOrder.setId(IdUtils.simpleUUID())
                .setOwnerUserId(SecurityUtils.getUserId())
                .setStatus(MxOrder.ORDER_STATUS_UN_COMPLETE)
                .setLoginStatus(MxOrder.LOGIN_STATUS_LOGIN)
                .setGoodsName("免息券")
                .setCookieRecordTime(now)
                .setCreateTime(now)
                .setPresetTime(now);// 抢购时间默认为当天
        return mxOrderMapper.insertMxOrder(mxOrder);
    }

    /**
     * 添加用户信息
     * @param mxOrder
     */
    private void addCustomerInfo(MxOrder mxOrder) {
        if (!ObjectUtils.isEmpty(mxOrder.getCreateUserId())) {
            //有用户ID
            SysCustomer sysCustomer = customerMapper.selectSysCustomerByCustomerId(mxOrder.getCreateUserId());;
            if (!ObjectUtils.isEmpty(sysCustomer)) {
                //存在添加订单信息
                mxOrder.setFishAccount(sysCustomer.getNickName()).setCustomerName(sysCustomer.getUserName()).setPhoneNumber(sysCustomer.getPhoneNum());
            }
        }
    }

    /**
     * 修改mx订单
     * 
     * @param mxOrder mx订单
     * @return 结果
     */
    @Override
    public int updateMxOrder(MxOrder mxOrder)
    {
        addCustomerInfo(mxOrder);
        int i = mxOrderMapper.updateMxOrder(mxOrder);

        //选择了用户同步更新京东信息和京东登录状态
        if (StringUtils.isNotEmpty(mxOrder.getCookie())) {
            this.updateOrderLoginStatusAsyn(mxOrder);
        }
        return i;
    }

    /**
     * 批量删除mx订单
     * 
     * @param ids 需要删除的mx订单主键
     * @return 结果
     */
    @Override
    public int deleteMxOrderByIds(String[] ids)
    {
        return mxOrderMapper.deleteMxOrderByIds(ids);
    }

    /**
     * 删除mx订单信息
     * 
     * @param id mx订单主键
     * @return 结果
     */
    @Override
    public int deleteMxOrderById(Integer id)
    {
        return mxOrderMapper.deleteMxOrderById(id);
    }

    @Override
    public int insertUserOrder(MxOrder mxOrder) {
        // 无用，废弃
        //判断用户是否已生成订单，生成订单后更新原有订单cookie
//        if (StringUtils.isEmpty(mxOrder.getCookie())) {
//            throw new CustomException("未获取到信息，请重试或联系工作人员");
//        }
//        List<MxOrder> mxOrders = mxOrderMapper.selectMxOrderList(new MxOrder().setCreateUserId(SecurityUtils.getUserId()));
//        Date now = DateUtils.getNowDate();
//        if (CollectionUtils.isEmpty(mxOrders)) {
//            String deptName = SecurityUtils.getLoginUser().getUser().getDept().getDeptName();
//            boolean is24User = deptName.contains("24期客户");
//            String mxType =  is24User? "1" : "2"; //1未24期 ，2代表24期
//            //未存在订单，生成订单
//            mxOrder.setId(IdUtils.simpleUUID()).setCreateUserId(SecurityUtils.getUserId())//用户id
//                    .setCookieRecordTime(now)
//                    .setStatus(MxOrder.ORDER_STATUS_UN_COMPLETE)
//                    .setLoginStatus(MxOrder.LOGIN_STATUS_LOGIN)
//                    .setGoodsName("免息券")
//                    .setMxType(mxType)
//                    .setGoodsName(is24User ? "24期免息" : "12期免息")
//                    /* .setOwnerUserId(SecurityUtils.getUserId())*/
//                    .setFishAccount(SecurityUtils.getLoginUser().getUser().getNickName()) //咸鱼名称为nickName
//                    .setCreateTime(now)
//                    .setPresetTime(now);// 抢购时间默认为当天
//                    //获取客户类型生成免息券类型
//
//            return mxOrderMapper.insertMxOrder(mxOrder);
//        } else {
//            //更新订单的cookie和登陆状态
//            mxOrders.forEach(order->order.setCookie(mxOrder.getCookie()).setCookieRecordTime(now).setLoginStatus(MxOrder.LOGIN_STATUS_LOGIN));
//            this.updateBatchById(mxOrders);
//            return 200;
//
//        }

        return 0;
    }

    @Override
    public int completeOrder(MxOrder mxOrder) {
        if (StringUtils.isEmpty(mxOrder.getCookie())) {
            throw new CustomException("未获取到cookie");
        }

        return  baseMapper.updateOrderToCompleteByCookie(mxOrder.getCookie());

    }

    /**
     * 管理员界面生成订单
     * @param
     * @return
     */
    @Override
    public int addAdminOrder(MxOrderVo vo) {
        if (StringUtils.isEmpty(vo.getActiveName())) {
            throw new CustomException("未选择添加订单模式");
        }
        if (StringUtils.isEmpty(vo.getCookie())) {
            throw new CustomException("未获取到cookie");
        }
        String cookie = vo.getCookie();
        String active = vo.getActiveName();
        Date now = DateUtils.getNowDate();
        if (MxOrderVo.ACTIVE_UPDATE.equals(active)) {
            //更新Cookie
            if (vo.getCreateUserId() == null) {
                throw new CustomException("未获取到用户id");
            }
            //有用户ID
            SysCustomer sysCustomer = customerMapper.selectSysCustomerByCustomerId(vo.getCreateUserId());
            if (ObjectUtils.isEmpty(sysCustomer)) {
                throw new CustomException("输入的用户ID未查询到的客户");
            }
            MxOrder mxOrder = new MxOrder();
            List<MxOrder> mxOrders = baseMapper.selectMxOrderList(mxOrder.setCreateUserId(sysCustomer.getCustomerId()));
            mxOrders.forEach(mxOrder1 -> mxOrder1.setCookie(cookie).setCookieRecordTime(now).setLoginStatus(MxOrder.LOGIN_STATUS_LOGIN));

            boolean b = this.updateBatchById(mxOrders);
            if (b) {
                //更新登录状态
                this.updateOrderLoginStatusAsyn(mxOrder);
            }
            return b ? 1 : 0;

        }

        //全品类
        String MX_SOURCE_QPL = "qpl";
        if (MxOrderVo.ACTIVE_ADD_USER_ORDER.equals(active)) {
            //添加新订单
            //更新Cookie
            if (vo.getCreateUserId() == null) {
                throw new CustomException("未获取到用户id");
            }
            //有用户ID
            SysCustomer sysCustomer = customerMapper.selectSysCustomerByCustomerId(vo.getCreateUserId());
            if (ObjectUtils.isEmpty(sysCustomer)) {
                throw new CustomException("输入的用户ID未查询到的用户");
            }
            //查询用户一分钟是否重复生成订单
            List<MxOrder> mxOrders = baseMapper.selectMxOrderList(new MxOrder().setCreateUserId(vo.getCreateUserId()));
            if (CollectionUtils.isNotEmpty(mxOrders)) {
                Date createTime = mxOrders.get(0).getCreateTime();
                long interval = now.getTime() - createTime.getTime();
                if (interval < 60 * 1000) {
                    //小于一分钟 不添加
                    throw new CustomException("一分钟内已添加过订单");
                }
            }
            MxOrder mxOrder = new MxOrder();
            String mxType = sysConfigService.getValueByKey("DEFAULT_MX_TYPE", "12","默认免息券类型"); ; // 获取默认免息券类型
            mxOrder.setMxType(mxType)
                    .setGoodsName(MxCouponType.getNameByType(mxType))
                    .setFishAccount(sysCustomer.getFishName())
                    .setId(IdUtils.simpleUUID())
                    .setCookieRecordTime(now)
                    .setCookie(cookie)
                    .setPhoneNumber(sysCustomer.getPhoneNum())
                    .setCustomerName(sysCustomer.getUserName())
                    .setStatus(MxOrder.ORDER_STATUS_UN_COMPLETE)
                    .setLoginStatus(MxOrder.LOGIN_STATUS_LOGIN)
                    .setGoodsName("免息券")
                    .setCreateTime(now)
                    .setCreateUserId(sysCustomer.getCustomerId())
                    .setOwnerUserId(SecurityUtils.getUserId())
                    .setMxSource(MX_SOURCE_QPL)
                    .setPresetTime(now);// 抢购时间默认为当天
                    //.setOwnerUserId(SecurityUtils.getUserId());//订单归属人

            int i = baseMapper.insertMxOrder(mxOrder);
            if (i > 0) {
                //更新登录状态
                this.updateOrderLoginStatusAsyn(mxOrder);
            }
            return i;

        }
        if (MxOrderVo.ACTIVE_ADD.equals(active)) {
            //添加新订单
            MxOrder mxOrder = new MxOrder();
            mxOrder.setId(IdUtils.simpleUUID())
                    .setCookieRecordTime(now)
                    .setCookie(cookie)
                    .setStatus(MxOrder.ORDER_STATUS_UN_COMPLETE)
                    .setLoginStatus(MxOrder.LOGIN_STATUS_LOGIN)
                    .setGoodsName("免息券")
                    .setCreateTime(now)
                    .setMxSource(MX_SOURCE_QPL)
                    .setPresetTime(now);// 抢购时间默认为当天
                    //.setOwnerUserId(SecurityUtils.getUserId());//订单归属人
            this.updateOrderLoginStatusAsyn(mxOrder);
            return baseMapper.insertMxOrder(mxOrder);
        }
        return 0;
    }

    /**
     * 根据权限获取订单列表
     * @param mxOrder
     * @return
     */
    @Override
    public List<MxOrder> selectMxOrderListByAuthority(MxOrder mxOrder) {
        Long userId = SecurityUtils.getUserId();
        //管理员查询全部
        boolean admin = SecurityUtils.isAdmin(userId);
        if (admin || LoginUserUtil.isSysAdmin()) {
            return mxOrderMapper.selectMxOrderList(mxOrder);
        }else {

            //用户查询个人订单
            if (LoginUserUtil.isMxUser()) {
                SysCustomer sysCustomer = customerMapper.selectSysCustomerByUserId(userId);
                if (ObjectUtils.isEmpty(sysCustomer)) {
                    throw new CustomException("未获取到用户信息");
                }
                mxOrder.setCreateUserId(sysCustomer.getCustomerId());
                return mxOrderMapper.selectMxOrderList(mxOrder);
            }
            //商家查询所管辖订单
            if (LoginUserUtil.isBusiness()) {
                mxOrder.setOwnerUserId(userId);
                return mxOrderMapper.selectMxOrderList(mxOrder);
            }
            //非上述角色
            throw new CustomException("未获取到用户信息或商家信息，请联系管理员");
        }
        //return null;
    }

    /**
     * 更新当前订单的最新状态
     * @param mxOrder
     * @return
     */
    @Override
    public int updateOrderLoginStatus(MxOrder mxOrder) {
        if (StringUtils.isEmpty(mxOrder.getCookie())) {
            throw new CustomException("未获取到订单信息");
        }
        String cookie = mxOrder.getCookie();
        String userInfo = JdUtils.getJdUser(cookie);
        if (StringUtils.isEmpty(userInfo)) {
            throw new CustomException("未获取到用户信息");
        }
        JSONObject jsonObject = JSONObject.parseObject(userInfo);
      /*  if (jsonObject.get("code").toString().equals("0")) {
            //Cookie失效，更新订单
            return baseMapper.updateOrderToReLoginByCookie(cookie);
        }*/
        //成功，获取用户信息
        JSONArray basicUserInfo = jsonObject.getJSONArray("basicUserInfo");
        List<jdUserInfoDto> jdUserInfoDtos = basicUserInfo.toJavaList(jdUserInfoDto.class);
        boolean successGetUser = false;
        for (jdUserInfoDto info : jdUserInfoDtos) {
            //用户名信息
            if ("nickNameInfo".equals(info.getFunctionId())) {
                successGetUser = true;
                if (StringUtils.isNotEmpty(info.getContent())) {
                    mxOrder.setJdAccount(info.getContent()).setLoginStatus(MxOrder.LOGIN_STATUS_LOGIN);
                    return baseMapper.updateMxOrderByCookie(mxOrder);
                } else {
                    //登陆失效
                    mxOrder.setLoginStatus(MxOrder.LOGIN_STATUS_RE_LOGIN);
                    return baseMapper.updateMxOrderByCookie(mxOrder);
                }

            }
        }

        return 0;
    }

    /**
     * 获取优惠券列表
     * @param mxOrder
     * @return
     */

    @Override
    public List<JdCouponDto> getCouponList(MxOrder mxOrder) {
        if (StringUtils.isEmpty(mxOrder.getCookie())) {
            throw new CustomException("未获取到订单信息");
        }
        String cookie = mxOrder.getCookie();
        String couPonInfo = JdUtils.getJdCoupon(cookie);
        JSONObject jsonObject = JSONObject.parseObject(couPonInfo);
        JSONArray basicUserInfo = jsonObject.getJSONArray("couponList");
        return basicUserInfo.toJavaList(JdCouponDto.class);
    }

    @Override
    public int changAddRebate(MxOrder mxOrder) {
        if (StringUtils.isEmpty(mxOrder.getId())) {
            throw new CustomException("未获取到订单id");
        }
        return  mxOrderMapper.changAddRebate(mxOrder.getId());
    }

    /**
     * 根据cookie更新订单登录状态
     * @param mxOrder
     * @return
     */
    @Override
    public int changAddRebateStatusByCookie(MxOrder mxOrder) {
        if (StringUtils.isEmpty(mxOrder.getCookie())) {
            throw new CustomException("未获取到cookie");
        }
        return  mxOrderMapper.changAddRebateByCookie(mxOrder.getCookie());
    }

    /**
     * 获取订单详细
     * @param id 订单id
     * @return 订单详细
     */
    @Override
    public MxOrderDetail getOrderDetail(String id) {
        MxOrder mxOrder = mxOrderMapper.selectMxOrderById(id);
        MxOrderDetail detail = new MxOrderDetail();
        BeanUtil.copyProperties(mxOrder,detail);
        if (!ObjectUtils.isEmpty(detail.getCreateUserId())){
            //有用户ID
            SysCustomer sysCustomer = customerMapper.selectSysCustomerByCustomerId(detail.getCreateUserId());
            detail.setSysCustomer(sysCustomer);
        }
        return detail;
    }

    @Override
    public void refreshTodayCookieStatus() {
        // 获取当前日期
        LocalDate today = LocalDate.now();

        // 转换为当天开始的 LocalDateTime
        LocalDateTime startOfDay = today.atStartOfDay();

        // 转换为Date类型
        Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());

        List<MxOrder> mxOrders = baseMapper.selectMxOrderList(new MxOrder().setPresetTime(startDate));
        mxOrders.forEach(this::updateOrderLoginStatus);
    }

    /**
     * 批量更新订单信息
     * @param vo
     */
    @Override
    public void batchUpdate(MxOrderVo vo) {
        List<String> batchIds = vo.getBatchIds();
        if (ObjectUtil.isEmpty(batchIds)) {
            throw new CustomException("未获取到订单id");
        }
        MxOrder updateOrder = new MxOrder();
        BeanUtil.copyProperties(vo, updateOrder);
        for (String batchId : batchIds) {
            this.updateMxOrder(updateOrder.setId(batchId));
        }
    }

    /**
     * 超级管理员可以查看全部，指定角色可以看指定范围的数据，其余只能查看归属为本人的数据
     * @param mxOrder
     * @return
     */
    @Override
    public List<MxOrder> selectMxOrderPageListByPermission(MxOrder mxOrder) {
        boolean admin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
        if (admin) {
            // sitia可以查看全部
            return this.selectMxOrderPageList(mxOrder);
        }
        for (SysRole role : SecurityUtils.getLoginUser().getUser().getRoles()) {
            if ("order_show_role".equals(role.getRoleKey())) {
                mxOrder.setAllShow("1");
                return this.selectMxOrderPageList(mxOrder);
            }
        }
        mxOrder.setOwnerUserId(SecurityUtils.getUserId());
        return  this.selectMxOrderPageList(mxOrder);
    }

    @Override
    public List<MxOrder> selectMxOrderPageList(MxOrder mxOrder) {
        if (mxOrder.getPresetTimes() != null) {
            mxOrder.setPresetTimeStar(mxOrder.getPresetTimes()[0]);
            mxOrder.setPresetTimeEnd(mxOrder.getPresetTimes()[1]);
        }
        return mxOrderMapper.selectMxOrderPageList(mxOrder);
    }

    /**
     * 异步更新订单登录状态
     * @param mxOrder
     * @return
     */
    @Async
    public int updateOrderLoginStatusAsyn(MxOrder mxOrder) {
        if (StringUtils.isEmpty(mxOrder.getCookie())) {
            throw new CustomException("未获取到订单信息");
        }
        String cookie = mxOrder.getCookie();
        String userInfo = JdUtils.getJdUser(cookie);
        if (StringUtils.isEmpty(userInfo)) {
            throw new CustomException("未获取到用户信息");
        }
        JSONObject jsonObject = JSONObject.parseObject(userInfo);
      /*  if (jsonObject.get("code").toString().equals("0")) {
            //Cookie失效，更新订单
            return baseMapper.updateOrderToReLoginByCookie(cookie);
        }*/
        //成功，获取用户信息
        JSONArray basicUserInfo = jsonObject.getJSONArray("basicUserInfo");
        List<jdUserInfoDto> jdUserInfoDtos = basicUserInfo.toJavaList(jdUserInfoDto.class);
        boolean successGetUser = false;
        for (jdUserInfoDto info : jdUserInfoDtos) {
            //用户名信息
            if ("nickNameInfo".equals(info.getFunctionId())) {
                successGetUser = true;
                if (StringUtils.isNotEmpty(info.getContent())) {
                    mxOrder.setJdAccount(info.getContent()).setLoginStatus(MxOrder.LOGIN_STATUS_LOGIN);
                    return baseMapper.updateMxOrderByCookie(mxOrder);
                } else {
                    //登陆失效
                    mxOrder.setLoginStatus(MxOrder.LOGIN_STATUS_RE_LOGIN);
                    return baseMapper.updateMxOrderByCookie(mxOrder);
                }

            }
        }

        return 0;
    }
}
